<template>
    <div class="login-background" @keyup.enter="handleEnterKey">
        <el-container :style="{ height: pcHeight }">
            <el-header height="60px" class="pd0 mg0 custom-header">
                <el-row type="flex" align="middle" class="h60">
                    <el-col :span="12">
                        <div class="fs20 bold pdL10">{{ projectName }}</div>
                    </el-col>
                    <el-col :span="12" class="textR pdR10"></el-col>
                </el-row>
            </el-header>

            <el-main class="pd0 mg0">
                <div class="flex-center" :style="{ height: pcHeight2 }">
                    <el-card class="pdR40 pdL40 overflow-y custom-card" style="width: 400px" v-if="loginType == 1">
                        <p class="fs18 textC">管理员登录</p>
                        <el-row class="pdB20">
                            <el-col :span="24" class="textL mgT20">
                                <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="80px">
                                    <el-form-item label="登录账号" prop="account">
                                        <el-input v-model="dataForm.account" maxlength="20" placeholder="请输入登录账号"
                                            clearable></el-input>
                                    </el-form-item>
                                    <el-form-item label="登录密码" prop="password" class="mgT20">
                                        <el-input password type="password" show-password v-model="dataForm.password"
                                            maxlength="20" placeholder="请输入登录账号密码" clearable></el-input>
                                    </el-form-item>
                                </el-form>
                            </el-col>
                            <el-col :span="24" type="flex" justify="center">
                                <el-button type="warning" class="h40 radius50 mgT10" style="opacity: 1; width: 100%"
                                    @click="submitForm(dataFormRef)" :disabled="btnSubmitFlag">{{ btnSubmitMsg
                                    }}</el-button>
                            </el-col>
                        </el-row>
                        <div class="textR pdB15">
                            <label>还没有账号，</label>
                            <label class="cursor" style="color: #ff9900;" @click="
                                (loginType = 2),
                                (btnSubmitMsg = '提交注册信息')
                                ">点我注册</label>
                        </div>
                    </el-card>
                    <el-card class="pdR40 pdL40 overflow-y custom-card" style="width: 400px" v-if="loginType == 2">
                        <p class="fs18 textC">注册账号</p>
                        <el-row class="pdB20">
                            <el-col :span="24" class="textL mgT20">
                                <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules"
                                    label-width="80px">
                                    <el-form-item label="账号" prop="account">
                                        <el-input v-model="registerForm.account" maxlength="20" placeholder="请输入登录账号"
                                            clearable></el-input>
                                    </el-form-item>
                                    <el-form-item label="账号密码" prop="password" class="mgT20">
                                        <el-input password type="password" show-password v-model="registerForm.password"
                                            maxlength="20" placeholder="请输入登录账号密码" clearable></el-input>
                                    </el-form-item>
                                    <el-form-item label="确认密码" prop="password2" class="mgT20">
                                        <el-input password type="password" show-password
                                            v-model="registerForm.password2" maxlength="20" placeholder="请输入确认密码"
                                            clearable></el-input>
                                    </el-form-item>
                                    <el-form-item label="昵称" prop="nick_name">
                                        <el-input v-model="registerForm.nick_name" maxlength="30" placeholder="请输入昵称"
                                            clearable show-word-limit></el-input>
                                    </el-form-item>
                                </el-form>
                            </el-col>
                            <el-col :span="24" type="flex" justify="center">
                                <el-button type="warning" class="h40 radius50 mgT10" style="opacity: 1; width: 100%"
                                    @click="submitFormReg(registerFormRef)" :disabled="btnSubmitFlag">{{ btnSubmitMsg
                                    }}</el-button>
                            </el-col>
                        </el-row>
                        <div class="textR pdB15">
                            <label>已有账号，</label>
                            <label class="cursor" style="color: #ff9900;" @click="
                                (loginType = 1), (btnSubmitMsg = '登 录')
                                ">点我登录</label>
                        </div>
                    </el-card>
                </div>
            </el-main>

            <el-footer height="60px" class="pd0 mg0 bgColorF custom-footer">
                <el-row type="flex" align="middle" class="h60 textC">
                    <el-col :span="24" class="color9 fs14">
                        {{ copyright }}
                    </el-col>
                </el-row>
            </el-footer>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from "vue";
import { useStore } from "vuex";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { setLocal, getLocal } from "@/store/funcs";

import user from "@/store/api/user";

const store = useStore();
const { proxy } = getCurrentInstance() as any;

const projectName = ref(process.env.VUE_APP_PROJECT_NAME || "XX系统");
const pcHeight = ref(document.body.clientHeight + "px");
const pcHeight2 = ref(document.body.clientHeight - 240 + "px");
const copyright = ref(
    "© " + new Date().getFullYear() + " 回忆你的倾听  版权所有      粤ICP备151XXX号"
);

const btnSubmitFlag = ref(false);
const btnSubmitMsg = ref("登 录");
const loginType = ref(1);

const dataFormRef = ref<FormInstance>() as any;
const dataForm = reactive({
    account: "",
    password: "",
});
const dataRules = reactive<FormRules<typeof dataForm>>({
    account: [
        { required: true, message: "请输入登录账号", trigger: "blur" },
        { min: 5, max: 20, message: "登录账号为5-20个字符", trigger: "blur" },
    ],
    password: [
        {
            required: true,
            message: "请输入登录账号密码",
            trigger: "blur",
        },
        {
            min: 5,
            max: 30,
            message: "登录账号密码为5-30个字符",
            trigger: "blur",
        },
    ],
});

const registerFormRef = ref<FormInstance>() as any;
const registerForm = reactive({
    account: "",
    password: "",
    password2: "",
    nick_name: "",
});
const validatePass = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("请输入注册账号的密码"));
    } else {
        if (registerForm.password2 !== "") {
            if (!registerFormRef.value) return;
        }
        callback();
    }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("再次输入密码"));
    } else if (value !== registerForm.password) {
        callback(new Error("二次密码不一致"));
    } else {
        callback();
    }
};
const registerRules = reactive<FormRules<typeof registerForm>>({
    account: [
        { required: true, message: "请输入登录账号", trigger: "blur" },
        { min: 5, max: 20, message: "登录账号为5-20个字符", trigger: "blur" },
    ],
    password: [
        { min: 6, max: 30, message: "密码长度为6-30个字符", trigger: "blur" },
        { validator: validatePass, trigger: "blur" },
    ],
    password2: [{ validator: validatePass2, trigger: "blur" }],
});

onMounted(() => {
    const myLocalData = getLocal("myLocalData");
    if (myLocalData && myLocalData.account) {
        proxy.$funcs.openPage(proxy.$funcs.getUrlParam("redirect") ?? "/main");
    }
});

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            btnSubmitFlag.value = true;
            btnSubmitMsg.value = "登录中...";
            const obj = {
                account: dataForm.account,
                password: dataForm.password,
            };
            const tmpResult: any = await user.apiLogin(obj);
            if (tmpResult.code === 1) {
                //登录成功，设置本地存储信息，并跳转到框架首页
                setLocal("myLocalData", {
                    account: dataForm.account,
                    nick_name: tmpResult.data.nick_name,
                });
                ElMessage.success(tmpResult.msg);
                proxy.$funcs.openPage(
                    proxy.$funcs.getUrlParam("redirect") ?? "/"
                );
            } else {
                ElMessage({
                    type: "error",
                    message: tmpResult.msg,
                });
            }
            btnSubmitFlag.value = false;
            btnSubmitMsg.value = "登 录";
        }
    });
};

const submitFormReg = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            btnSubmitFlag.value = true;
            btnSubmitMsg.value = "注册中...";
            const obj = {
                account: registerForm.account,
                password: registerForm.password,
                nick_name: registerForm.nick_name,
            };
            const tmpResult: any = await user.apiRegister(obj);
            if (tmpResult.code === 1) {
                loginType.value = 1;
                btnSubmitMsg.value = "登 录";
                formEl.resetFields(); //重置注册表单字段内容
                ElMessage.success(tmpResult.msg);
            } else {
                btnSubmitMsg.value = "提交注册信息";
                ElMessage({
                    type: "error",
                    message: tmpResult.msg,
                });
            }
            btnSubmitFlag.value = false;
        }
    });
};

const handleEnterKey = () => {
    if (loginType.value === 1) {
        submitForm(dataFormRef.value);
    } else if (loginType.value === 2) {
        submitFormReg(registerFormRef.value);
    }
};

onUnmounted(() => { });
</script>

<style scoped>
.login-background {
    background-image: url('@/assets/images/backgroundpic.png');
    background-size: cover;
    background-position: center;
    height: 100vh;
}

.custom-header {
    background-color: rgba(255, 255, 255, 0.8);
    /* 半透明白色背景 */
    border-bottom: none;
    /* 去掉底部边框 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 添加轻微阴影 */
}

.custom-card {
    background-color: rgba(255, 255, 255, 0.8);
    /* 半透明白色背景 */
    border: none;
    /* 去掉边框 */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    /* 添加轻微阴影 */
}

.custom-footer {
    background-color: rgba(255, 255, 255, 0.8);
    /* 半透明白色背景 */
    border-top: none;
    /* 去掉顶部边框 */
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
    /* 添加轻微阴影 */
}
</style>
